package csx.study.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import csx.study.demo.dto.Result;
import csx.study.demo.dto.VoucherDTO;
import csx.study.demo.entity.SeckillVoucher;
import csx.study.demo.entity.Voucher;
import csx.study.demo.mapper.VoucherMapper;
import csx.study.demo.service.ISeckillVoucherService;
import csx.study.demo.service.IVoucherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static csx.study.demo.utils.RedisConstants.SECKILL_STOCK_KEY;


//在实际开发中，有时DTO和VO的界限并不严格，有些项目可能只使用一种（如DTO）来贯穿多层
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author csx
 * @since 2025-03-03
 */
@Service
public class VoucherServiceImpl extends ServiceImpl<VoucherMapper, Voucher> implements IVoucherService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryVoucherOfShop(Long shopId) {
        // 查询优惠券信息
        List<VoucherDTO> vouchers = getBaseMapper().queryVoucherOfShop(shopId);
        // 返回结果
        return Result.ok(vouchers);
    }

    @Override
    @Transactional
    public Result addSeckillVoucher(VoucherDTO voucherDTO) {
        Voucher voucher = BeanUtil.toBean(voucherDTO, Voucher.class);
        // 保存优惠券
        save(voucher);
        // 保存秒杀信息
        SeckillVoucher seckillVoucher = new SeckillVoucher();
        seckillVoucher.setVoucherId(voucher.getId());
        seckillVoucher.setStock(voucherDTO.getStock());
        seckillVoucher.setBeginTime(voucherDTO.getBeginTime());
        seckillVoucher.setEndTime(voucherDTO.getEndTime());
        seckillVoucherService.save(seckillVoucher);

        stringRedisTemplate.opsForValue().set(SECKILL_STOCK_KEY + voucher.getId(), voucherDTO.getStock().toString());
        return Result.ok(voucher.getId());
    }

    @Override
    public Result addVoucher(VoucherDTO voucherDTO) {
        Voucher voucher = BeanUtil.toBean(voucherDTO, Voucher.class);
        save(voucher);
        return Result.ok(voucher.getId());
    }
}
